<?php

namespace App\Http\Controllers;

use App\Exceptions\AppException;
use App\Models\District;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class DistrictController extends Controller
{
    /**
     * 填报单位列表
     */
    public function list(Request $request)
    {
        $query = District::query();
        if (!empty($request->id)) {
            $query->where(['id' => $request->id]);
        }
        if (Auth::user()->district_id != District::CITY_ID) {
            $query->where(['id' => Auth::user()->district_id]);
        }
        $pageSize = isset($request->page_size) ? $request->page_size : 10;
        $response = $query->orderBy('id', 'asc')->paginate($pageSize);
        return responder()->success($response);
    }

    public function create(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:30',
        ]);
        if (Auth::user()->district_id != District::CITY_ID) {
            throw new AppException('没有权限');
        }
        $exists = District::whereName($request->name)->exists();
        if ($exists) {
            throw new AppException('已存在');
        }
        $model = new District;
        $model->name = $request->name;
        if ($request->id) {
            $model->id = $request->id;
        }
        $model->save();
        return responder()->success();
    }

    public function update(Request $request)
    {
        $request->validate([
            'id' => 'required|exists:districts,id,deleted_at,NULL',
            'name' => 'required|string',
        ]);
        if (Auth::user()->district_id != District::CITY_ID) {
            throw new AppException('没有权限');
        }
        $exists = District::where('id', '！=', $request->id)->whereName($request->name)->exists();
        if ($exists) {
            throw new AppException('已存在');
        }
        $model = District::find($request->id);
        $model->name = $request->name;
        $model->save();
        return responder()->success();
    }

    public function delete(Request $request)
    {
        $request->validate([
            'id' => 'required|exists:districts,id,deleted_at,NULL',
        ]);
        if (Auth::user()->district_id != District::CITY_ID) {
            throw new AppException('没有权限');
        }
        District::find($request->id)->delete();
        return responder()->success();
    }
}
